<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\controller\Util;
use app\common\library\Sms;
use app\common\model\User;
use fast\Random;
use think\Db;

use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Hook;

/**
 * 助教
 *
 * @icon fa fa-circle-o
 */
class Helper extends Backend
{

    /**
     * Helper模型对象
     * @var \app\admin\model\Helper
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Helper;
        $this->view->assign("sexList", $this->model->getSexList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $id = $this->auth->id;
        $group = Db::name('auth_group_access')->where('uid', $id)->find()['group_id'];
        $this->view->assign("group",$group);
    }
    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $id = $this->auth->id;
            $group = Db::name('auth_group_access')->where('uid', $id)->find()['group_id'];
            if ($group === 2) {
                $teacher = Db::name('teacher')->where('admin_id', $id)->find();
                $where1['teacher_id'] = $teacher['id'];

                $total = $this->model
                    ->where($where)
                    ->where($where1)
                    ->order($sort, $order)
                    ->count();

                $list = $this->model
                    ->where($where)
                    ->where($where1)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            }

            foreach ($list as $row) {
                $row->visible(['id', 'teacher_id', 'name', 'phone', 'nick_name', 'header', 'money',
                    'age', 'last_login_time', 'new_message_num', 'new_notification_num', 'create_time',
                    'invite_code', 'english_name', 'account_status', 'user_id', 'admin_id']);

            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }


    private function addHelper2Admin($username, $password, $email = '', $mobile = '', $nick_name = '', $extend = [])
    {


        //账号注册时需要开启事务,避免出现垃圾数据
        try {

            $params['username'] = $username;
            $params['nickname'] = $nick_name;
            $params['status'] = "hidden";
            $params['salt'] = Random::alnum();
            $params['password'] = md5(md5($password) . $params['salt']);
            $params['avatar'] = '/assets/img/avatar.png'; //设置新管理员默认头像。
            Db::name("admin")->insert($params);
            return Db::getLastInsID();
        } catch (\Exception $e) {

            $this->error($e->getMessage());
            Db::rollback();
            return false;
        }

    }

    private function addHelper2User($username, $password, $email = '', $mobile = '', $nick_name = '', $extend = [])
    {
        if (User::getByUsername($username)) {
            $this->error('Username already exist');
            return false;
        }

        if ($mobile && User::getByMobile($mobile)) {
            $this->error('Mobile already exist');
            return false;
        }

        $ip = request()->ip();
        $time = time();

        $data = [
            'username' => $username,
            'nickname' => $nick_name,
            'password' => $password,
            'email' => $email,
            'mobile' => $mobile,
            'level' => 1,
            'score' => 0,
            'avatar' => '',
            'group_id' => '3'
        ];
        $params = array_merge($data, [
            'salt' => Random::alnum(),
            'jointime' => $time,
            'joinip' => $ip,
            'logintime' => $time,
            'loginip' => $ip,
            'prevtime' => $time,
            'status' => 'normal'
        ]);

        $params['password'] = $this->getEncryptPassword($password, $params['salt']);

        $params = array_merge($params, $extend);

        $user = User::create($params, true);
        return $user;
    }

    /**
     * 获取密码加密后的字符串
     * @param string $password 密码
     * @param string $salt 密码盐
     * @return string
     */
    private function getEncryptPassword($password, $salt = '')
    {
        return md5(md5($password) . $salt);
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $myparams = $this->request->post("row/a");
            if ($myparams) {
                $myparams = $this->preExcludeFields($myparams);
                // 数据校验START
                $data = $this->validate($myparams, [
                    'phone' => 'require|regex:/^1[3456789]\d{9}$/',
                    'password' => 'require|regex:/^[0-9a-z_.]{8,16}$/i',
                ], [
                        'phone.require' => '手机号码必填',
                        'phone.regex' => '手机号码格式错误',
                        'password.require' => '密码为必填',
                        'password.regex' => '密码格式为8-16位大小写字母、数字、特殊符号',
                    ]
                );
                if (!empty($data) && $data !== true) {
                    return $this->error($data);
                }
                $res = Db::name('admin')->where('username',$myparams['phone'])->find();
                if(!empty($res)){
                    $this->error('该账号已注册');
                }
                //$smsResult = Sms::check($myparams['phone'],$myparams['code'],'register');
               // $smsResult ?: $this->error("验证码错误");
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $myparams[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {

                    //教师添加助教
                    // 数据校验END
                    // 插入user表
                    $param['phone'] = $myparams['phone'];
                    $param['password'] = $myparams['password'];
                    $param['nick_name'] = $myparams['nick_name'];
                    $param['header'] = $myparams['header'];
                    //添加到user表，同时添加group_id
//                    $ret = $this->addHelper2User($param['phone'], $param['password'], '', $param['phone'], $param['nick_name'], []);
//                    $user = $ret;
//                    if ($ret) {
                        //  res作为admin的id标识   插入admin表
                        $ret = $this->addHelper2Admin($param['phone'], $param['password'], '', $param['phone'], $param['nick_name'], []);
                        //助教角色 4
                        Db::name("auth_group_access")->insert(['uid' => $ret, 'group_id' => 4]);
//                    }
                    if ($ret) {
                        $params['invite_code'] = Util::getInviteCode();
//                        $params['user_id'] = $user['id'];
                        $params['user_id'] = 0;
                        $params['admin_id'] = $ret;
                        $params['account_status'] = 0;
                        $params['phone'] = $param['phone'];
                        $params['nick_name'] = $param['nick_name'];
                        $params['name'] = $param['phone'];
                        $params['header'] = $param['header'];
                        $params['register_time'] = date("Y-m-d H:i:s");
//                        查询老师
                        $user_id = $this->auth->id;
                        if ($user_id) {
                            $teacher = Db::name('teacher')->where('admin_id', $user_id)->find();
                            if ($teacher) {
                                $params['teacher_id'] = $teacher['id'];
                            } else {
                                throw new Exception('当前用户不是老师');
                            }
                        }
                        //            插入helper表
                        $result = Db::name('helper')->insert($params);
                        $tid = Db::name("helper")->getLastInsID();
                        $hooks_data = [
                            // 用户姓名
                            'name' => '助教',
                            // 用户所在表id
                            'uid' => $tid,
                            // 用户类型 student / teacher / help
                            'type' => 'help',
                        ];
                        $data = Hook::listen("createAccountForUser", $hooks_data, '', true);
                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $teacher = Db::name('teacher')->where('admin_id',$this->auth->id)->find();
        $this->assign('invite_code',$teacher['invite_code']);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $params['account_status'] = input('account_status');
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $mystatus = $params['account_status'];
                    $params['id'] = input("ids");
                    $helper = Db::name('helper')->where('id', $params['id'])->find();
                    Util::changeAdminOrUser($helper['admin_id'], $mystatus, '');
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function selectpage()
    {
        return parent::selectpage(); // TODO: Change the autogenerated stub
    }

}
